﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using System.Security.Claims;
using Volo.Abp.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using System.Text.Json;
using Ebusiness_OrderService.Repositorys;
using Ebusiness_Authservice.Services.Dtos;
using OpenIddict.EntityFrameworkCore.Models;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories;
using OpenIddict.Core;
using System;
using Volo.Abp.Security.Claims;
using IdentityModel;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System.Security.Principal;


namespace Ebusiness_Authservice.Controllers
{
    [ApiController]
    [Route("connect")]
    public class ConnectController : AbpController
    {
        public IOpenIddictApplicationManager _applicationManager { get; set; }
        public IOpenIddictScopeManager _scopeManager { get; set; }
        public IOpenIddictTokenManager _tokenManager { get; set; }
        public IOpenIddictAuthorizationManager _authorizationManager { get; set; }

        public OpenIddictTokenManager<OpenIddictEntityFrameworkCoreToken> openIddictTokenManager { get; set; }
        public IAuthserRepository AuthserRepository { get; set; }

        public IMemoryCache _cache { get; set; } // 添加缓存服务
        //private readonly ApplicationDbContext _context;

        public ConnectController()
        {

        }

        /// <summary>
        /// 授权端点 - /connect/authorize
        /// 处理用户授权同意页面，实现授权码流程
        /// https://localhost:44392/connect/authorize?response_type=code&client_id=website&redirect_uri=http://localhost:4200&scope=OrderService Product offline_access&state=xyz
        /// </summary>
        [HttpGet("authorize")]
        public async Task<IActionResult> Authorize()
        {
            var request = HttpContext.GetOpenIddictServerRequest();
            if (request == null)
            {
                return BadRequest("无效的OpenID Connect请求");
            }

            // 验证客户端
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);
            if (application == null)
            {
                return BadRequest("无效的客户端");
            }

            // 检查用户是否已登录
            if (!User.Identity?.IsAuthenticated == true)
            {
                // 用户未登录，重定向到登录页面
                // 将授权请求参数保存到缓存中，登录成功后继续授权流程
                var authRequestKey = Guid.NewGuid().ToString();
                var authRequest = new AuthorizationRequest
                {
                    ClientId = request.ClientId,
                    RedirectUri = request.RedirectUri,
                    Scope = request.Scope,
                    State = request.State,
                    ResponseType = request.ResponseType,
                    Nonce = request.Nonce
                };

                // 缓存授权请求，设置5分钟过期
                _cache.Set(authRequestKey, authRequest, TimeSpan.FromMinutes(5));

                // 重定向到登录页面，传递授权请求的key
                return RedirectToAction("Login", "Auth", new
                {
                    returnUrl = $"/connect/authorize?auth_key={authRequestKey}"
                });
            }

            // 用户已登录，检查是否已有授权
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            var cacheKey = $"user_auth_{userId}_{request.ClientId}";

            if (_cache.TryGetValue(cacheKey, out bool hasAuthorized) && hasAuthorized)
            {
                // 用户之前已授权，直接返回授权码
                return await ProcessAuthorization(request, userId);
            }

            // 用户未授权，显示授权同意页面
            var scopes = new List<string>();
            if (!string.IsNullOrEmpty(request.Scope))
            {
                scopes = request.Scope.Split(' ').ToList();
            }
            var applications = application as OpenIddictEntityFrameworkCoreApplication;
            return View("authorizecode", new AuthorizeViewModel
            {
                ClientId = request.ClientId,
                ClientName = applications.DisplayName ?? request.ClientId,
                State = request.State,
                Scope = request.Scope,
                Scopes = scopes,
                ReturnUrl = Request.Path + Request.QueryString,
                RedirectUri = request.RedirectUri
                //AuthRequestKey = Request.Query["auth_key"].ToString()
            });
        }

        /// <summary>
        /// 处理授权同意 - POST /connect/authorize
        /// https://localhost:44392/connect/authorize?response_type=code&client_id=website&redirect_uri=http://localhost:4200&scope=OrderService Product offline_access&state=xyz
        /// </summary>
        [HttpPost("authorize")]
        [Authorize]
        public async Task<IActionResult> AuthorizePost([FromForm] string action, [FromForm] string client_id, [FromForm] string redirect_uri, [FromForm] string response_type, [FromForm] string scope, [FromForm] string state)
        {
            if (string.IsNullOrEmpty(action))
            {
                return BadRequest("缺少action参数");
            }
            // 获取OpenIddict请求
            var request = HttpContext.GetOpenIddictServerRequest();
            if (request == null)
            {
                return BadRequest("无效的OpenID Connect请求");
            }

            // 添加调试日志
            Console.WriteLine($"收到授权请求: action={action}, scope={request.Scope}, client_id={request.ClientId}");

            // 验证必要参数
            if (string.IsNullOrEmpty(request.ClientId))
            {
                return BadRequest("缺少client_id参数");
            }

            if (action == "deny")
            {
                // 用户拒绝授权
                return Forbid(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
            }

            // 用户同意授权
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (string.IsNullOrEmpty(userId))
            {
                return BadRequest("无效的用户标识");
            }

            // 缓存用户授权状态，避免重复授权
            var cacheKey = $"user_auth_{userId}_{request.ClientId}";
            _cache.Set(cacheKey, true, TimeSpan.FromDays(30)); // 30天内无需重新授权

            Console.WriteLine($"用户 {userId} 同意授权给客户端 {request.ClientId}");

            // 处理授权并返回授权码
            return await ProcessAuthorization(request, userId);
        }

        /// <summary>
        /// 令牌端点 - /connect/token
        /// 处理授权码换取访问令牌
        /// </summary>
        [HttpPost("token")]
        public async Task<IActionResult> Token()
        {
            //获取客户端请求
            var request = HttpContext.GetOpenIddictServerRequest();
            if (request == null)
            {
                return BadRequest("无效的OpenID Connect请求");
            }
            
            // 根据授权类型处理不同的流程
            switch (request.GrantType)
            {
                case "authorization_code":   //授权码模式
                    return await HandleAuthorizationCodeFlow(request);
                case "refresh_token":  //刷新token
                    return await HandleRefreshTokenFlow(request);
                case "client_credentials":   //客户端模式
                    return await HandleClientCredentialsFlow(request);
                case "password":             // 密码模式
                    return await HandlePasswordFlow(request);
                default:
                    return BadRequest("不支持的授权类型");
            }
        }

        /// <summary>
        /// 用户信息端点 - /connect/userinfo
        /// 返回当前用户的详细信息  (未完成)
        /// </summary>
        [HttpGet("userinfo")]
        [Authorize(AuthenticationSchemes = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)]
        public async Task<IActionResult> UserInfo()
        {
            var subject = User.FindFirst(OpenIddictConstants.Claims.Subject)?.Value;
            if (string.IsNullOrEmpty(subject))
            {
                return BadRequest("无效的用户标识");
            }

            // 获取用户信息
            var user = await AuthserRepository.FirstOrDefaultAsync(u => u.Id == Guid.Parse(subject));
            if (user == null)
            {
                return NotFound("用户不存在");
            }

            // 返回用户信息（根据请求的作用域过滤）
            var userInfo = new Dictionary<string, object>
            {
                ["sub"] = user.Id,
                ["name"] = user.UserName,
                ["email"] = user.Email
            };

            // 如果请求了角色作用域，添加角色信息
            if (User.HasScope("roles"))
            {
                userInfo["roles"] = user.Roles;
            }

            return Ok(userInfo);
        }

        /// <summary>
        /// 令牌内省端点 - /connect/introspect
        /// 验证令牌的有效性和获取令牌信息  (未完成)
        /// </summary>
        [HttpPost("introspect")]
        public async Task<IActionResult> Introspect([FromForm] string token)
        {

            if (string.IsNullOrEmpty(token))
            {
                return BadRequest("令牌不能为空");
            }

            // 查找令牌
            var tokenEntity = await _tokenManager.FindByIdAsync(token);
            if (tokenEntity == null)
            {
                return Ok(new { active = false });
            }

            // 检查令牌是否有效 - 修正验证方法
            var isValid = await ValidateTokenAsync(tokenEntity);
            if (!isValid)
            {
                return Ok(new { active = false });
            }

            // 获取令牌信息 - 使用修正后的方法
            var tokenInfo = await GetTokenInfoAsync(tokenEntity);
            if (tokenInfo == null)
            {
                return Ok(new { active = false });
            }

            return Ok(new
            {
                active = true,
                scope = tokenInfo.Scope,
                client_id = tokenInfo.ClientId,
                username = tokenInfo.Username,
                exp = tokenInfo.ExpiresAt,
                iat = tokenInfo.IssuedAt
            });
        }

        /// <summary>
        /// 令牌回收端点 - /connect/revoke
        /// 回收指定的令牌 (未完成)
        /// </summary>
        [HttpPost("revoke")]
        public async Task<IActionResult> Revoke([FromForm] string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return BadRequest("令牌不能为空");
            }

            // 查找令牌
            var tokenEntity = await _tokenManager.FindByIdAsync(token);
            if (tokenEntity != null)
            {
                // 回收令牌
                await _tokenManager.TryRevokeAsync(tokenEntity);
                return Ok(new { message = "令牌已回收" });
            }

            return Ok(new { message = "令牌无效或已回收" });
        }

        /// <summary>
        /// 用户退出
        /// </summary>
        /// <returns></returns>
        [HttpGet("endsession")]
        public virtual async Task<IActionResult> GetAsync()
        {
            // Ask ASP.NET Core Identity to delete the local and external cookies created
            // when the user agent is redirected from the external identity provider
            // after a successful authentication flow (e.g Google or Facebook).
            await HttpContext.SignOutAsync();

            // Returning a SignOutResult will ask OpenIddict to redirect the user agent
            // to the post_logout_redirect_uri specified by the client application or to
            // the RedirectUri specified in the authentication properties if none was set.
            return SignOut(authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
        }

        #region 私有方法

        /// <summary>
        /// 处理授权码流程
        /// </summary>
        private async Task<IActionResult> HandleAuthorizationCodeFlow(OpenIddictRequest request)
        {
            //这句代码的核心作用是：
            //主动认证：使用OpenIddict的认证方案对当前请求进行认证
            //获取用户主体：从认证结果中提取包含用户信息的Principal对象
            //验证令牌：确保请求中的令牌（如授权码）是有效的
            //获取用户信息：从Principal中提取用户ID、用户名等声明信息
            // 使用OpenIddict认证方案验证授权码
            var principal2 = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;

            if (principal2?.Identity?.IsAuthenticated != true)
            {
                return BadRequest("授权码无效或已过期");
            }

            // 获取用户信息
            var userId = principal2.FindFirst(OpenIddictConstants.Claims.Subject)?.Value;
            var user = await AuthserRepository.FirstOrDefaultAsync(u => u.Id == Guid.Parse(userId));

            //获取相关信息 
            //var tokenInfo = (await _tokenManager.FindByIdAsync(principal2.FindFirst(OpenIddictConstants.Claims.Private.TokenId)?.Value)) as OpenIddictEntityFrameworkCoreToken;
            //var authorizationInfo = await _authorizationManager.FindByIdAsync(principal2.FindFirst(OpenIddictConstants.Claims.Private.AuthorizationId)?.Value);

            if (user == null)
            {
                return BadRequest("用户不存在");
            }

            // 创建新的访问令牌
            var claims = new List<Claim>
                 {
                     new(OpenIddictConstants.Claims.Subject, user.Id.ToString()),
                     new(OpenIddictConstants.Claims.Username, user.UserName),
                     new(OpenIddictConstants.Claims.Email, user.Email),
                     new(OpenIddictConstants.Claims.Role, string.Join(",", user.Roles)),
                     new(OpenIddictConstants.Claims.ClientId, request.ClientId)
                 };

            var identity = new ClaimsIdentity(claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
            var newPrincipal = new ClaimsPrincipal(identity);

            //获取信息
            var xx = principal2.FindAll(OpenIddictConstants.Claims.Private.Scope);
            List<string> sco = xx.Select(x => x.Value).ToList();
            List<string> aud = new List<string>();
            foreach (var i in sco)
            {
                var sc = (await _scopeManager.FindByNameAsync(i)) as OpenIddictEntityFrameworkCoreScope;
                if (sc != null)
                {
                    List<string> s = JsonSerializer.Deserialize<List<string>>(sc.Resources) ?? new List<string>();
                    foreach (var item in s)
                    {
                        aud.Add(item);
                    }
                }
            }
            // ⭐ 这里显式设置 Audience
            //newPrincipal.SetAudiences("OrderService_resource_server");
            // 设置多个受众
            newPrincipal.SetAudiences(aud.Distinct().ToList());

            // 如果还需要 Scope：
            //newPrincipal.SetScopes("OrderService");
            // 设置 Scope（可选）
            newPrincipal.SetScopes(sco);

            return SignIn(newPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
        }

        /// <summary>
        /// 处理刷新令牌流程
        /// </summary>
        private async Task<IActionResult> HandleRefreshTokenFlow(OpenIddictRequest request)
        {
            //这句代码的核心作用是：
            //主动认证：使用OpenIddict的认证方案对当前请求进行认证
            //获取用户主体：从认证结果中提取包含用户信息的Principal对象
            //验证令牌：确保请求中的令牌（如授权码）是有效的
            //获取用户信息：从Principal中提取用户ID、用户名等声明信息
            // 使用OpenIddict认证方案验证授权码
            var principal2 = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;

            if (principal2?.Identity?.IsAuthenticated != true)
            {
                return BadRequest("授权码无效或已过期");
            }

            // 获取用户信息
            var userId = principal2.FindFirst(OpenIddictConstants.Claims.Subject)?.Value;
            var user = await AuthserRepository.FirstOrDefaultAsync(u => u.Id == Guid.Parse(userId));

            //获取相关信息 
            //var tokenInfo = (await _tokenManager.FindByIdAsync(principal2.FindFirst(OpenIddictConstants.Claims.Private.TokenId)?.Value)) as OpenIddictEntityFrameworkCoreToken;
            //var authorizationInfo = await _authorizationManager.FindByIdAsync(principal2.FindFirst(OpenIddictConstants.Claims.Private.AuthorizationId)?.Value);

            if (user == null)
            {
                return BadRequest("用户不存在");
            }

            // 创建新的访问令牌
            var claims = new List<Claim>
                 {
                     new(OpenIddictConstants.Claims.Subject, user.Id.ToString()),
                     new(OpenIddictConstants.Claims.Username, user.UserName),
                     new(OpenIddictConstants.Claims.Email, user.Email),
                     new(OpenIddictConstants.Claims.Role, string.Join(",", user.Roles)),
                     new(OpenIddictConstants.Claims.ClientId, request.ClientId)
                 };

            var identity = new ClaimsIdentity(claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
            var newPrincipal = new ClaimsPrincipal(identity);

            //获取信息
            var xx = principal2.FindAll(OpenIddictConstants.Claims.Private.Scope);
            List<string> sco = xx.Select(x => x.Value).ToList();
            List<string> aud = new List<string>();
            foreach (var i in sco)
            {
                var sc = (await _scopeManager.FindByNameAsync(i)) as OpenIddictEntityFrameworkCoreScope;
                if (sc != null)
                {
                    List<string> s = JsonSerializer.Deserialize<List<string>>(sc.Resources) ?? new List<string>();
                    foreach (var item in s)
                    {
                        aud.Add(item);
                    }
                }
            }
            // ⭐ 这里显式设置 Audience
            //newPrincipal.SetAudiences("OrderService_resource_server");
            // 设置多个受众
            newPrincipal.SetAudiences(aud.Distinct().ToList());

            // 如果还需要 Scope：
            //newPrincipal.SetScopes("OrderService");
            // 设置 Scope（可选）
            newPrincipal.SetScopes(sco);

            return SignIn(newPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
        }

        /// <summary>
        /// 密码模式
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private async Task<IActionResult> HandlePasswordFlow(OpenIddictRequest request)
        {
            // 1. 校验参数
            if (string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password))
                return BadRequest("用户名或密码不能为空");

            // 2. 查询用户（使用异步 + 不跟踪）
            var user = await AuthserRepository.FirstOrDefaultAsync(u => u.UserName == request.Username);

            if (user == null || !BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
                return Forbid(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

            // 3. 构造声明（包含sub为用户ID）
            var claims = new List<Claim>
            {
                new(OpenIddictConstants.Claims.Subject, user.Id.ToString()),
                new(OpenIddictConstants.Claims.Username, user.UserName),
                new(OpenIddictConstants.Claims.Email, user.Email),
                new(OpenIddictConstants.Claims.Role, string.Join(",", user.Roles)),
                new(OpenIddictConstants.Claims.ClientId, request.ClientId ?? string.Empty),
                // 可选：受众，多受众可重复添加多条
                new(OpenIddictConstants.Claims.Audience, "resource_server")
            };

            var identity = new ClaimsIdentity(
                claims,
                OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

            var principal = new ClaimsPrincipal(identity);

            // 4. 设置作用域（若需要刷新令牌，确保包含 offline_access）
            if (!string.IsNullOrEmpty(request.Scope))
                principal.SetScopes(request.Scope.Split(' '));

            //获取信息
            List<string> sco = request.GetScopes().ToList();
            List<string> aud = new List<string>();
            foreach (var i in sco)
            {
                var sc = (await _scopeManager.FindByNameAsync(i)) as OpenIddictEntityFrameworkCoreScope;
                if (sc != null)
                {
                    List<string> s = JsonSerializer.Deserialize<List<string>>(sc.Resources) ?? new List<string>();
                    foreach (var item in s)
                    {
                        aud.Add(item);
                    }
                }
            }
            // ⭐ 这里显式设置 Audience
            //newPrincipal.SetAudiences("OrderService_resource_server");
            // 设置多个受众
            principal.SetAudiences(aud.Distinct().ToList());

            // 5. 返回令牌（access_token，若包含offline_access则也会返回refresh_token）
            return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
        }

        /// <summary>
        /// 处理客户端凭据流程
        /// </summary>
        private async Task<IActionResult> HandleClientCredentialsFlow(OpenIddictRequest request)
        {
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);
            var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType, OpenIddictConstants.Claims.PreferredUsername, OpenIddictConstants.Claims.Role);

            if (application == null)
            {
                throw new InvalidOperationException(L["TheApplicationDetailsCannotBeFound"]);
            }
            identity.AddClaim(OpenIddictConstants.Claims.Subject, await _applicationManager.GetClientIdAsync(application));
            identity.AddClaim(OpenIddictConstants.Claims.PreferredUsername, await _applicationManager.GetDisplayNameAsync(application));

            var principal = new ClaimsPrincipal(identity);

            principal.SetScopes(request.GetScopes());

            //获取信息
            List<string> sco = request.GetScopes().ToList();
            List<string> aud = new List<string>();
            foreach (var i in sco)
            {
                var sc = (await _scopeManager.FindByNameAsync(i)) as OpenIddictEntityFrameworkCoreScope;
                if (sc != null)
                {
                    List<string> s = JsonSerializer.Deserialize<List<string>>(sc.Resources) ?? new List<string>();
                    foreach (var item in s)
                    {
                        aud.Add(item);
                    }
                }
            }
            //设置受众
            principal.SetResources(aud);

            // 创建访问令牌
            return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
        }

        /// <summary>
        /// 处理授权并返回授权码
        /// </summary>
        private async Task<IActionResult> ProcessAuthorization(OpenIddictRequest request, string userId)
        {
            // 创建用户声明
            var user = await AuthserRepository.FirstOrDefaultAsync(u => u.Id == Guid.Parse(userId));
            if (user == null)
            {
                return BadRequest("用户不存在");
            }

            var claims = new List<Claim>
        {
            new(OpenIddictConstants.Claims.Subject, user.Id.ToString()),
            new(OpenIddictConstants.Claims.Username, user.UserName),
            new(OpenIddictConstants.Claims.Email, user.Email),
            new(OpenIddictConstants.Claims.Role, string.Join(",", user.Roles))
        };

            var identity = new ClaimsIdentity(claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);

            // 设置请求的作用域
            if (!string.IsNullOrEmpty(request.Scope))
            {
                principal.SetScopes(request.Scope.Split(' '));
            }
            // 使用OpenIddict创建授权票据
            // OpenIddict会自动生成授权码并重定向到ReturnUrl
            // OpenIddict自动处理 - 当调用 SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme) 时，OpenIddict会自动：
            //生成授权码
            //重定向到 ReturnUrl
            //在查询字符串中包含 code 和 state 参数
            return SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
        }

        /// <summary>
        /// 验证令牌有效性 - 修正后的方法 (作废)
        /// </summary>
        private async Task<bool> ValidateTokenAsync(object tokenEntity)
        {
            try
            {
                // 获取验证结果
                var validationResults = _tokenManager.ValidateAsync(tokenEntity);

                // 检查是否有验证错误
                var hasErrors = false;
                await foreach (var result in validationResults)
                {
                    //if (result.)
                    //{
                    //    hasErrors = true;
                    //    break;
                    //}
                }

                return !hasErrors;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取令牌信息 - 修正后的方法，只使用可用的API (作废)
        /// </summary>
        private async Task<TokenInfo?> GetTokenInfoAsync(object tokenEntity)
        {
            try
            {
                // 只使用确定存在的方法
                var tokenId = await _tokenManager.GetIdAsync(tokenEntity);
                var tokenType = await _tokenManager.GetTypeAsync(tokenEntity);
                var tokenSubject = await _tokenManager.GetSubjectAsync(tokenEntity);

                // 获取令牌的过期时间和创建时间（如果可用）
                DateTimeOffset? expiresAt = null;
                DateTimeOffset? issuedAt = null;

                try
                {
                    expiresAt = await _tokenManager.GetExpirationDateAsync(tokenEntity);
                }
                catch
                {
                    // 方法不存在，忽略
                }

                try
                {
                    issuedAt = await _tokenManager.GetCreationDateAsync(tokenEntity);
                }
                catch
                {
                    // 方法不存在，忽略
                }

                // 简化处理：使用默认作用域，不调用不存在的GetScopesAsync方法
                var scope = "api1"; // 默认作用域

                return new TokenInfo
                {
                    Id = tokenId,
                    Type = tokenType,
                    Subject = tokenSubject,
                    ClientId = "unknown", // 简化处理
                    Scope = scope,
                    ExpiresAt = expiresAt?.ToString("yyyy-MM-ddTHH:mm:ssZ"),
                    IssuedAt = issuedAt?.ToString("yyyy-MM-ddTHH:mm:ssZ"),
                    Username = tokenSubject // 使用subject作为username
                };
            }
            catch
            {
                return null;
            }
        }
        #endregion
    }
}
